<?php
//FanWe服务
class FanweServices
{
	function __construct()
	{

	}

	function Login($user,$pwd)
	{
		$pwd = md5($pwd);

		$count = DB::resultFirst("SELECT count(*) FROM ".DB::table('admin')." WHERE adm_name='$user' and adm_pwd='$pwd' and status = 1");

		if(intval($count) > 0)
		{
			$_SESSION['adm_name'] = $user;
			return 1;
		}
		else
			return 0;
	}

	function Logout()
	{
		unset($_SESSION['adm_name']);
		return true;
	}

	function GetServiceData($type,$begin)
	{
		$result = array();

		switch($type)
		{
			case 'sites':
				$sql = "SELECT s.id,s.cate_id,s.city_id,gc.name as city_name,s.name,s.site_key,
						s.url,s.sort as site_sort,s.is_sync FROM ".DB::table('site')." AS s 
						LEFT JOIN ".DB::table('group_city')." AS gc ON gc.id = s.city_id 
						LEFT JOIN ".DB::table('site_rules')." AS sr ON sr.id = s.id AND sr.name = 'collect_url' 
						WHERE s.status = 1 AND s.close_collect = 0 AND sr.rule <> '' 
						GROUP BY s.id ORDER BY s.id ASC LIMIT $begin,1000";

				$res = DB::query($sql);
				while($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

			case 'rules':
				$sql = "SELECT id,name,rule FROM ".DB::table('site_rules')." LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$data['rule'] = stripslashes($data['rule']);
					$result[] = $data;
				}
			break;

			case 'siteCates':
				$sql = "SELECT id,name,sort as cate_sort FROM ".DB::table('site_cate')." WHERE status = 1 ORDER BY id ASC LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

			case 'goodsCates':
				$sql = "SELECT id,name,sort as cate_sort,keywords,is_default FROM ".DB::table('goods_cate')." WHERE status = 1 ORDER BY id ASC LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

			case 'groupCitys':
				$sql = "SELECT id,name,sort as city_sort FROM ".DB::table('group_city')." WHERE status = 1 ORDER BY id ASC LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

			case 'citySites':
				$sql = "SELECT site_id,city_id,sort as sc_sort FROM ".DB::table('city_site')." LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

			case 'cityAreas':
				$sql = "SELECT id,name,city_id,parent_id,sort as area_sort FROM ".DB::table('business_circle')." LIMIT $begin,1000";
				$res = DB::query($sql);
				while ($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;
		}

		return $result;
	}

	function GetCollectSiteList()
	{
		$sites = array();

		$sql = 'SELECT s.id,s.cate_id,s.name,s.site_key,s.url,s.sort as site_sort,s.is_sync 
				FROM '.DB::table('site').' AS s 
				LEFT JOIN '.DB::table('site_rules').' AS sr ON sr.id = s.id AND sr.name = \'collect_url\' 
				WHERE s.status = 1 AND sr.rule <> \'\' ORDER BY s.id ASC';

		$site_res = DB::query($sql);
		while ($site = DB::fetch($site_res))
		{
			$rules_res = DB::query("SELECT id,name,rule FROM ".DB::table('site_rules')." WHERE id = '$site[id]'");
			while ($rule = DB::fetch($rules_res))
			{
				$rule['rule'] = stripslashes($rule['rule']);
				$site['rules'][] = $rule;
			}

			$sites[] = $site;
		}

		return $sites;
	}

	function UploadInit()
	{
		DB::query("DELETE FROM ".DB::table('cron')." WHERE type='goods'");
		DB::query('TRUNCATE TABLE '.DB::table('collect_temp'));
		DB::query('REPLACE INTO '.DB::table('collect_temp').' 
				SELECT g.id,g.site_id,g.collect_key,g.collect_url,g.collect_name 
				FROM '.DB::table('goods_key').' as gk 
				INNER JOIN '.DB::table('goods').' as g ON g.id = gk.id 
				WHERE gk.end_time > '.getTodayTime());

		S('goods')->checkGoodsRangeExist();
		return true;
	}

	function UploadGoods($list)
	{
		$results = array();
        include_once import('function/time');

        foreach($list as $goods)
        {
            usleep(100);

            $result = array();
            $result['id'] = $goods->id;
            $result['group_index'] = $goods->group_index;
            $result['isError'] = 0;
            $result['msg'] = '';

            try
            {
                if(empty($goods->name) || !parseUrl($goods->url) || intval($goods->site_id) == 0)
                {
                     $result['isError'] = 1;
                     $result['msg'] = "名称为空或链接格式错误";
                     $results[] = $result;
                     continue;
                }

                $result_goods = array();

                $goods->bought = intval(trim(strip_tags($goods->bought)));
                $goods->shop_price = floatval(trim(strip_tags($goods->shop_price)));
                $goods->market_price = floatval(trim(strip_tags($goods->market_price)));

                $time = gmtTime();

                if(isset($goods->custom_time) && !empty($goods->custom_time))
                {
                    $end_time = str2Time($goods->custom_time);
                }
                else
                {
                    $END_TIME = $goods->end_time;
                    $END_TIME1 = $goods->end_time1;
                    $NOW_TIME = str2Time($goods->collect_time);

                    if(!empty($goods->end_time_ext))
                        eval("\$end_time = ".$goods->end_time_ext.";");
                    else
                    {
                        if (!empty($END_TIME) && !is_numeric($END_TIME))
                            $end_time = str2Time($END_TIME);
                        elseif(preg_match("/^(?P<year>\d{4})(?P<month>\d{2})(?P<date>\d{2})(?P<hour>\d{2})(?P<minute>\d{2})(?P<second>\d{2})$/",$END_TIME))
                            $end_time = str2Time($END_TIME);
                        else if(strlen($END_TIME) > 11)
                            $end_time = substr($END_TIME,0,10);
                        else
                            $end_time = $END_TIME;
                    }

                    if($end_time > 0)
                        $end_time = $end_time - intval($goods->time_zone) * 3600;
                }

                if($end_time <= $time)
                {
                     $result['isError'] = 2;
                     $result['msg'] = "团购已结束";
                     $results[] = $result;
                     continue;
                }

                $result['end_time'] = $end_time;

				$goods_id = 0;

				$goods->name = addslashes(trim(strip_tags($goods->name)));
                $goods->collect_key = addslashes(trim(strip_tags($goods->collect_key)));
                $goods->url = addslashes(trim(strip_tags($goods->url)));
				if(!empty($goods->collect_key))
				{
					$goods_id = DB::resultFirst("SELECT id FROM ".DB::table('collect_temp')." 
							WHERE collect_url ='".$goods->url."' 
							AND collect_key = '".$goods->collect_key."' 
							AND site_id = ".$goods->site_id);
				}
				else
				{
					$res = DB::query("SELECT id,collect_name FROM ".DB::table('collect_temp')." 
							WHERE collect_url ='".$goods->url."' AND site_id = ".$goods->site_id." 
							ORDER BY id DESC");
					while($data = DB::fetch($res))
					{
						similar_text($goods->name,$data['collect_name'],$percent);
						if($percent >= 85)
						{
							$goods_id = $data['id'];
							break;
						}
					}
				}

                if($goods_id > 0)
                {
                    //$min_time = getTodayTime();
                    $old_goods = DB::fetchFirst("SELECT name,shop_price,market_price,end_time,bought,collect_name FROM ".DB::table('goods')." WHERE id = ".$goods_id);

                    if($old_goods)
                    {
                        $set_sql = "";

						$is_update_match = false;

                        if($old_goods['name'] == $old_goods['collect_name'] && $old_goods['name'] != $goods->name)
						{
                            $set_sql.= ",name = '".$goods->name."',collect_name = '".$goods->name."'";
							$is_update_match = true;
						}
                        if(floatval($old_goods['shop_price']) != $goods->shop_price)
                            $set_sql.= ",shop_price = '".$goods->shop_price."'";

                        if(floatval($old_goods['market_price']) != $goods->market_price)
                            $set_sql.= ",market_price = '".$goods->market_price."'";

                        if(intval($old_goods['bought']) != $goods->bought)
                            $set_sql.= ",bought = '".$goods->bought."'";

                        if(intval($old_goods['end_time']) != intval($end_time))
                            $set_sql.= ",end_time = '".$end_time."'";

                        if($set_sql != "")
                        {
                            $set_sql = substr($set_sql, 1);
                            DB::query("UPDATE ".DB::table('goods')." SET $set_sql WHERE id = ".$goods_id);
							if($is_update_match)
							{
								$match_content = segmentToUnicode(clearSymbol($goods->site_name.$goods->name));
								DB::query("UPDATE ".DB::table('goods_match')." SET content = '$match_content' WHERE id = ".$goods_id);
								DB::query("UPDATE ".DB::table('goods_now_match')." SET content = '$match_content' WHERE id = ".$goods_id);
							}
                        }

                        $result['goods_id'] = $goods_id;
                        $results[] = $result;
                        continue;
                    }
                    else
                    {
                        $result['isError'] = 2;
                        $result['msg'] = "服务器没有此团购数据";
                        $results[] = $result;
                        continue;
                    }
                }

                if (!empty($goods->begin_time) && !is_numeric($goods->begin_time))
                    $begin_time = str2Time($goods->begin_time);
                elseif(preg_match("/^(?P<year>\d{4})(?P<month>\d{2})(?P<date>\d{2})(?P<hour>\d{2})(?P<minute>\d{2})(?P<second>\d{2})$/",$END_TIME))
                    $end_time = str2Time($END_TIME);
                else if(strlen($goods->begin_time) > 11)
                    $begin_time = substr($goods->begin_time,0,10);
                else
                    $begin_time = $goods->begin_time;

                if($goods->is_down_img == 1 && parseUrl($goods->small_img))
                {
                    $imgs = $this->SaveGoodsImage($goods->small_img);

                    if($imgs === false)
                    {
                        $small_img = addslashes($goods->small_img);
                        $big_img = addslashes($goods->small_img);
                    }
                    else
                    {
                        $small_img = $imgs['small'];
                        $big_img = $imgs['big'];
                    }
                }
                else
                {
                    $small_img = $goods->small_img;
                    $big_img = $goods->small_img;
                }


                $goods->cate_id = intval($goods->cate_id);
                $goods->brief = addslashes($goods->brief);
                $goods->content = addslashes($goods->content);
				$goods->site_name = addslashes($goods->site_name);
                $goods->city = addslashes(trim(strip_tags($goods->city)));

                $sql = "INSERT INTO ".DB::table('goods')." (site_id,site_name,cate_id,name,city,url,shop_price,market_price,end_time,small_img,big_img,sort,add_time,update_time,bought,collect_key,collect_url,collect_name,brief,content,begin_time,r_sort,cr_sort) VALUES(".$goods->site_id.",'".$goods->site_name."',".$goods->cate_id.",'".$goods->name."','".$goods->city."','".$goods->url."','".$goods->shop_price."','".$goods->market_price."','".$end_time."','".$small_img."','".$big_img."',".$goods->collect_sort.",$time,$time,'".$goods->bought."','".$goods->collect_key."','".$goods->url."','".$goods->name."','".$goods->brief."','".$goods->content."','".$begin_time."','0','0')";
				if(DB::query($sql) !== false)
				{
					$goods_id = DB::insertId();

					$sql = "REPLACE INTO ".DB::table('goods_key')." (id, site_id, city, cate_id, sort, r_sort, cr_sort, end_time) VALUES(".$goods_id.",".$goods->site_id.",'".$goods->city."',".$goods->cate_id.",".$goods->collect_sort.",0,0,".$end_time.")";
					DB::query($sql);

					$sql = "INSERT INTO ".DB::table('collect_temp')." (id, site_id, collect_key, collect_url, collect_name) VALUES(".$goods_id.",".$goods->site_id.",'".$goods->collect_key."','".$goods->url."','".$goods->name."')";
					DB::query($sql);

					DB::query('REPLACE INTO '.DB::table('goods_match').'(id,content) VALUES('.$goods_id.',\''.segmentToUnicode(clearSymbol($goods->site_name.$goods->name)).'\')');

					DB::query('REPLACE INTO '.DB::table('goods_now_match').'(id,content) VALUES('.$goods_id.',\''.segmentToUnicode(clearSymbol($goods->site_name.$goods->name)).'\')');

					$result['goods_id'] = $goods_id;
					$results[] = $result;

					if(is_array($goods->shops))
					{
						foreach($goods->shops as $shop)
						{
							if(!empty($shop->lon) && $shop->lon != "empty" && !empty($shop->lat) && $shop->lat != "empty")
							{
                                if(empty($shop->name))
                                    $shop->name = $goods->site_name;

								$sql = "INSERT INTO ".DB::table('suppliers')." (goods_id,name,address,tel,area,longitude,latitude,end_time) VALUES(".$goods_id.",'".$shop->name."','".$shop->address."','".$shop->tel."','".$shop->area."','".$shop->lon."','".$shop->lat."','".$end_time."')";

								DB::query($sql);
							}
						}
					}

					if(!empty($goods->areas))
					{
						$areas = explode(',',$goods->areas);
						foreach($areas as $area)
						{
							$sql = "INSERT INTO ".DB::table('goods_area')." (goods_id,city,area,end_time) VALUES(".$goods_id.",'".$goods->city."','".$area."','".$end_time."')";
							DB::query($sql);
						}
					}
				}
				else
				{
					$result['isError'] = 1;
					$result['msg'] = "添加今日团购失败";
					$results[] = $result;
					if(!parseUrl($big_img))
					{
						unlink(ROOT_PATH.$big_img);
						unlink(ROOT_PATH.$small_img);
					}
				}
            }
            catch(Exception $e)
            {
                $result['isError'] = 1;
                $result['msg'] = "执行发生错误";
                $results[] = $result;
                continue;
            }
        }

		return $results;
	}

	function SaveGoodsImage($imgurl)
	{
		require_once('image.php');
		global $_FANWE;
		$imgWidth = $_FANWE['setting']['small_width'];
		$imgHeight = $_FANWE['setting']['small_height'];

		$dir = date('Ym');
        $dir = FANWE_ROOT.'public/upload/goods/'.$dir.'/origin/';

        if (!file_exists($dir))
        {
            if (!makeDir($dir))
                return false;
        }

		$extArr= explode('.',$imgurl);
		$extArr = array_reverse($extArr);

		if(count($extArr) == 0)
			$ext = ".jpg";
		else
		{
			$ext = ".".strtolower($extArr[0]);

			if($ext != ".jpg" && $ext != ".jpeg"  && $ext != ".gif" && $ext != ".giff" && $ext != ".png" && $ext != ".bmp")
				$ext = ".jpg";
		}

		$img_name = uniqid();
        $img_name = $dir . $img_name . $ext;

		if (copy($imgurl, $img_name))
		{
			$big = str_replace(FANWE_ROOT,'/', str_replace('\\', '/', realpath($img_name)));

			$img = new Image();

			$small = $img->MakeThumb($img_name,$imgWidth,$imgHeight);

			return array("big"=>$big,"small"=>$small);
		}
		else
			return false;
	}

	function GetSiteListByKeywords($keywords)
	{
		$sites = array();
		$keywords = mysqlLikeQuote(trim($keywords));

		if(!empty($keywords))
			$sql = "SELECT id,name FROM ".DB::table('site')." WHERE name LIKE '%$keywords%' OR site_key LIKE '%$keywords%' OR url LIKE '%$keywords%' LIMIT 0,30";
		else
			$sql = "SELECT id,name FROM ".DB::table('site')." WHERE is_sync = 0 LIMIT 0,30";

		$res = DB::query($sql);
		while ($site = DB::fetch($res))
		{
			$sites[] = $site;
		}

		return $sites;
	}

	function SyncSiteRule($groupNav)
	{
		DB::update('sys_conf',array('val'=>$groupNav['version']),"name='SITE_RULE_VERSION'");

		$sites = array();

		foreach($groupNav['sites'] as $site)
		{
			$siteID = DB::resultFirst("SELECT id FROM ".DB::table('site')." WHERE site_key='".$site['site_key']."'");

			if(intval($siteID) > 0)
			{
				DB::update('site',array('is_sync'=>1),"id='$siteID'");
				DB::delete('site_rules',"id='$siteID'");

				foreach($site['rules'] as $key => $rule)
				{
					DB::insert('site_rules',array(
						'id'=>$siteID,
						'name'=>$rule['name'],
						'rule'=>$rule['rule']
					));

					$site['rules'][$key]['rule'] = stripslashes($rule['rule']);
				}

				$sites[] = array("id"=>$siteID,"rules"=>$site['rules']);
			}
		}

		return $sites;
	}

	//更新规则到站点
	function UpdateSiteRule($siteID,$siteKey,$rules,$isEdit = false )
	{
		if($isEdit)
			$ruleList = array();

		if($siteID > 0 && !empty($siteKey))
		{
			DB::update('site',array('is_sync'=>1,'site_key'=>$siteKey),"id='$siteID'");
			DB::delete('site_rules',"id='$siteID'");

			foreach($rules as $key => $value)
			{
				if($value != "")
				{
					if($isEdit)
					{
						$value = stripslashes($value);
						$ruleList[] = array("name"=>$key,"rule"=>$value);
						$value = addslashes($value);
					}

					DB::insert('site_rules',array(
						'id'=>$siteID,
						'name'=>$key,
						'rule'=>$value
					));
				}
			}
		}

		if($isEdit)
			return $ruleList;
		else
			return true;
	}

	//下载站点
	function InsertSiteRule($site)
	{
		$siteID = DB::insert('site',array(
						'name'=>$site['name'],
						'site_key'=>$site['site_key'],
						'url'=>$site['url'],
						'status'=>1,
						'is_sync'=>1,
						'sort'=>$site['site_sort'],
						'cate_id'=>$site['cate_id'],
						'city_id'=>$site['city_id'],
						'is_best'=>$site['is_best']
					),true);

		foreach($site['rules'] as $key => $value)
		{
			DB::insert('site_rules',array(
				'id'=>$siteID,
				'name'=>$key,
				'rule'=>$value
			));
		}

		return true;
	}

	//下载站点列表
	function InsertSitesRule($cateID,$sort,$sites)
	{
		foreach($sites as $site)
		{
			$siteID = DB::insert('site',array(
						'name'=>$site['name'],
						'site_key'=>$site['site_key'],
						'url'=>$site['url'],
						'status'=>1,
						'is_sync'=>1,
						'sort'=>$sort,
						'cate_id'=>$cateID,
						'city_id'=>0,
						'is_best'=>0
					),true);

			foreach($site['rules'] as $key => $value)
			{
				DB::insert('site_rules',array(
					'id'=>$siteID,
					'name'=>$key,
					'rule'=>$value
				));
			}
		}

		return true;
	}

	function GetWebInfo($tooltip)
	{
		$result = array();

		$sql = "SELECT COUNT(id) FROM ".DB::table('message')." WHERE rec_module='Site' AND id > ".$tooltip->web;
		$result['info']['web'] = intval(DB::resultFirst($sql));

		$sql = "SELECT MAX(id) FROM ".DB::table('message')." WHERE rec_module='Site'";
		$tooltip->web = intval(DB::resultFirst($sql));

		$sql = "SELECT COUNT(id) FROM ".DB::table('message')." WHERE rec_module='Feedback' AND id > ".$tooltip->feedback;
		$result['info']['feedback'] = intval(DB::resultFirst($sql));

		$sql = "SELECT MAX(id) FROM ".DB::table('message')." WHERE rec_module='Feedback'";
		$tooltip->feedback = intval(DB::resultFirst($sql));

		$sql = "SELECT COUNT(id) FROM ".DB::table('message')." WHERE rec_module='SiteMessage' AND id > ".$tooltip->siteMessage;
		$result['info']['siteMessage'] = intval(DB::resultFirst($sql));

		$sql = "SELECT MAX(id) FROM ".DB::table('message')." WHERE rec_module='SiteMessage'";
		$tooltip->siteMessage = intval(DB::resultFirst($sql));

		$result["tooltip"] = $tooltip;
		return $result;
	}

	function ClearHtmls()
	{
		S('Goods')->runCron();
	}

	function GetTableStructure()
	{
		global $_FANWE;
		$res = DB::query("SHOW TABLES LIKE '".mysqlLikeQuote($_FANWE['config']['db'][1]['tablepre'])."%'");
		$all_tables = array();
		while($data = DB::fetch($res))
		{
			$all_tables[] = $data;
		}

		$tables = array();
		DB::query('SET SQL_QUOTE_SHOW_CREATE = 0');
		foreach ($all_tables as $key => $table)
        {
			$item = array();
			$table = current($table);
			$create_sql = "DROP TABLE IF EXISTS $table;\r\n";
			$tmp_arr = DB::fetchFirst("SHOW CREATE TABLE $table");
			$tmp_sql = $tmp_arr['Create Table'];
			$tmp_sql = substr($tmp_sql, 0, strrpos($tmp_sql, ")") + 1); //去除行尾定义。
        	$tmp_sql = str_replace("\n", "\r\n", $tmp_sql);
			$create_sql .= $tmp_sql . " ENGINE=MyISAM;\r\n";

			$item['name'] = $table;
      		$item['count'] = intval(DB::resultFirst("SELECT COUNT(*) FROM $table"));
			$item['checked'] = 1;
			$item['status'] = '未备份';
			$item['create'] = $create_sql;

			$tables[] = $item;
        }

		return $tables;
	}

	function GetTableData($table,$pos,$size)
	{
		$dump_sql = "";

		/* 获取数据表记录总数 */
        $total = intval(DB::resultFirst("SELECT COUNT(*) FROM $table"));
		if ($total - $pos < 0)
       		return $dump_sql;

		/* 获取数据库数据 */

		$res = DB::query("SELECT * FROM $table LIMIT " . $pos . ', ' . $size);
		$data_list = array();
		while($data = DB::fetch($res))
		{
			$data_list[] = $data;
		}

		$data_count = count($data_list);
		$fields = array_keys($data_list[0]);
        $start_sql = "INSERT INTO $table ( `" . implode("`, `", $fields) . "` ) VALUES ";

		/* 循环将数据写入 */
		for($j=0; $j< $data_count; $j++)
		{
			$record = array_map("dumpEscapeString", $data_list[$j]);//过滤非法字符
			$tmp_dump_sql = $start_sql . " (". $this->ImplodeInsertValues($record) .");\r\n";
			$dump_sql.= $tmp_dump_sql;
		}

		return $dump_sql;
	}

	function RestoreTable($sql_str)
	{
		$except_table = array();
		//'DROP TABLE IF EXISTS '. DB_PREFIX . 'sessions',
        //'CREATE TABLE '. DB_PREFIX . 'sessions',
        //'INSERT INTO '. DB_PREFIX . 'sessions',

		$sql_str = str_replace("\r", '', $sql_str);
		$ret = explode(";\n", $sql_str);
        $ret_count = count($ret);

		/* 执行sql语句 */
        for($i = 0; $i < $ret_count; $i++)
		{
			$ret[$i] = trim($ret[$i], " \r\n;"); //剔除多余信息
			if (strpos($ret[$i], 'CREATE TABLE') !== false)
			{
				$ret[$i] .= " DEFAULT CHARSET=utf8";
			}

			if (!empty($ret[$i]))
			{
				$tmp_sql = str_replace('`', '', $ret[$i]);

				if ($this->StrPosa(trim($tmp_sql), $except_table) === 0)
				{
					continue;
				}

				if(DB::query($ret[$i]) === false)
					return false;
			}
		}

        return true;
	}

	function CheckTable()
	{
		$result = array();
		$res = DB::query("SHOW TABLES LIKE '".mysqlLikeQuote($_FANWE['config']['db'][1]['tablepre'])."%'");
		$all_tables = array();
		while($data = DB::fetch($res))
		{
			$all_tables[] = current($data);
		}

		if(count($all_tables) > 0)
		{
			$res = DB::query("CHECK TABLE ".implode(',',$all_tables));
			while($data = DB::fetch($res))
			{
				$data['Table'] = explode('.',$data['Table']);
				$data['Table'] = $data['Table'][1];
				$result[] = $data;
			}
		}

		return $result;
	}

	function RepairTable($table)
	{
		$result = DB::fetchFirst("REPAIR TABLE ".$table);
		return $result;
	}

    function GetGroupData($type,$begin)
    {
        $result = array();

		switch($type)
		{
			case 'now':
				$sql = "SELECT id as a,site_id as b,city as c,sort as d,r_sort as e,cr_sort f,end_time as g,collect_name as h,collect_url as i,collect_key as j FROM ".DB::table('goods_now')." GROUP BY id LIMIT $begin,1000";

				$res = DB::query($sql);
				while($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;

            case 'today':
                $min_time = getTodayTime();

                $sql = "SELECT id as a,site_id as b,city as c,sort as d,r_sort as e,cr_sort f,end_time as g,collect_name as h,collect_url as i,collect_key as j FROM ".DB::table('goods').
                        " WHERE status = 1 AND end_time >= '$min_time' GROUP BY id LIMIT $begin,1000";

				$res = DB::query($sql);
				while($data = DB::fetch($res))
				{
					$result[] = $data;
				}
			break;
        }

        return $result;
    }

	function GetGroupDataSites()
	{
		DB::query('TRUNCATE TABLE '.DB::table('collect_temp'));
        $goods_ids = array();
        $res = DB::query('SELECT g.url,GROUP_CONCAT(gk.id) AS ids,COUNT(gk.id) AS gcount 
                        FROM '.DB::table('goods_key').' AS gk 
                        INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id 
                        WHERE gk.end_time > '.getTodayTime().' GROUP BY g.url HAVING gcount > 1');
        while($goods = DB::fetch($res))
		{
			$ids = explode(',',$goods['ids']);
            array_pop($ids);
            $goods_ids = array_merge($goods_ids,$ids);
		}

		if(count($goods_ids) > 0)
		{
			$ids_where = implode(',',$goods_ids);
			DB::query('DELETE FROM '.DB::table('goods_key').' WHERE id IN ('.$ids_where.')');
			DB::query('DELETE FROM '.DB::table('goods').' WHERE id IN ('.$ids_where.')');
			DB::query('DELETE FROM '.DB::table('suppliers').' WHERE goods_id IN ('.$ids_where.')');
			DB::query('DELETE FROM '.DB::table('goods_area').' WHERE goods_id IN ('.$ids_where.')');
			DB::query('DELETE FROM '.DB::table('goods_match').' WHERE id IN ('.$ids_where.')');
		}

		DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		DB::query("TRUNCATE TABLE ".DB::table('goods_now'));
		DB::query('REPLACE INTO '.DB::table('goods_now').'(id, site_id, site_name, name, city, cate_id, url, click_count, best_count, collect_count, shop_price, market_price, begin_time, end_time, brief, sort, small_img, big_img, score, is_best, bought, collect_buy, ef_time, post_count, r_sort, cr_sort, add_time) SELECT g.id, g.site_id, site_name, name, g.city, g.cate_id, url, click_count, best_count, collect_count, shop_price, market_price, begin_time, g.end_time, brief, g.sort, small_img, big_img, score, is_best, bought, collect_buy, ef_time, post_count, g.r_sort, g.cr_sort, add_time FROM '.DB::table('goods_key').' AS gk INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id WHERE g.status = 1 AND gk.end_time > '.TIME_UTC);

		DB::query("TRUNCATE TABLE ".DB::table('goods_now_key'));
		DB::query('INSERT INTO '.DB::table('goods_now_key').' SELECT id,site_id,city,cate_id,sort,r_sort,cr_sort,0,0,0,0,end_time FROM '.DB::table('goods_now'));

		$sort_sites = array();

		$res = DB::query('SELECT site_id FROM '.DB::table('goods_key').'
				WHERE end_time > '.getTodayTime().' GROUP BY site_id');

		while($sid = DB::fetch($res))
		{
			$sort_sites[] = $sid['site_id'];
		}

		return $sort_sites;
	}

    function UpdateGroupData($site_id)
    {
		global $_FANWE;
		loadCache('goods');

        DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		DB::query('REPLACE INTO '.DB::table('goods_temp').' 
				SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time 
				FROM '.DB::table('goods_now_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t 
				WHERE site_id = '.$site_id.' ORDER BY sort ASC,id DESC');

		if(DB::affectedRows() > 0)
		{
			$goods_cate_citys = array();
			$goods_cates = array();
			$goods_citys = array();
			$sql = '';
			$sql_jg = '';
			$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
			while($goods = DB::fetch($res))
			{
				$cr_sort = 0;
				$d_sort = 0;
				$dc_sort = 0;
				$e_sort = 0;
				$ec_sort = 0;

				$city = $goods['city'];
				if(!isset($goods_citys[$city]))
					$goods_citys[$city] = 0;
				$goods_citys[$city]++;
				$cr_sort = $goods_citys[$city];

				$cate_id = $goods['cate_id'];
				$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
				if(!isset($goods_cates[$cate_id]))
					$goods_cates[$cate_id] = 0;
				$goods_cates[$cate_id]++;

				if(!isset($goods_cate_citys[$cate_id][$city]))
					$goods_cate_citys[$cate_id][$city] = 0;
				$goods_cate_citys[$cate_id][$city]++;

				$parent_id = $cate['pid'];
				if($parent_id > 0)
				{
					$e_sort = $goods_cates[$cate_id];
					$ec_sort = $goods_cate_citys[$cate_id][$city];

					if(!isset($goods_cates[$parent_id]))

						$goods_cates[$parent_id] = 0;
					$goods_cates[$parent_id]++;

					$d_sort = $goods_cates[$parent_id];

					if(!isset($goods_cate_citys[$parent_id][$city]))
						$goods_cate_citys[$parent_id][$city] = 0;
					$goods_cate_citys[$parent_id][$city]++;

					$dc_sort = $goods_cate_citys[$parent_id][$city];
				}
				else
				{
					$d_sort = $goods_cates[$cate_id];
					$dc_sort = $goods_cate_citys[$cate_id][$city];
				}

				$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
				$sql_jg = ',';
			}

			if($sql != '')
			{
				DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
				DB::query('REPLACE INTO '.DB::table('goods_now_key').' SELECT * FROM '.DB::table('goods_temp'));
			}
		}

		usleep(10);
		DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		DB::query('REPLACE INTO '.DB::table('goods_temp').' 
				SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time 
				FROM '.DB::table('goods_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t 
				WHERE site_id = '.$site_id.' AND end_time > '.getTodayTime().' 
				ORDER BY sort ASC,id DESC');
		if(DB::affectedRows() > 0)
		{
			$goods_cate_citys = array();
			$goods_cates = array();
			$goods_citys = array();
			$sql = '';
			$sql_jg = '';
			$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
			while($goods = DB::fetch($res))
			{
				$cr_sort = 0;
				$d_sort = 0;
				$dc_sort = 0;
				$e_sort = 0;
				$ec_sort = 0;

				$city = $goods['city'];
				if(!isset($goods_citys[$city]))
					$goods_citys[$city] = 0;
				$goods_citys[$city]++;
				$cr_sort = $goods_citys[$city];

				$cate_id = $goods['cate_id'];
				$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
				if(!isset($goods_cates[$cate_id]))
					$goods_cates[$cate_id] = 0;
				$goods_cates[$cate_id]++;

				if(!isset($goods_cate_citys[$cate_id][$city]))
					$goods_cate_citys[$cate_id][$city] = 0;
				$goods_cate_citys[$cate_id][$city]++;

				$parent_id = $cate['pid'];
				if($parent_id > 0)
				{
					$e_sort = $goods_cates[$cate_id];
					$ec_sort = $goods_cate_citys[$cate_id][$city];

					if(!isset($goods_cates[$parent_id]))
						$goods_cates[$parent_id] = 0;
					$goods_cates[$parent_id]++;

					$d_sort = $goods_cates[$parent_id];

					if(!isset($goods_cate_citys[$parent_id][$city]))
						$goods_cate_citys[$parent_id][$city] = 0;
					$goods_cate_citys[$parent_id][$city]++;

					$dc_sort = $goods_cate_citys[$parent_id][$city];
				}
				else
				{
					$d_sort = $goods_cates[$cate_id];
					$dc_sort = $goods_cate_citys[$cate_id][$city];
				}

				$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
				$sql_jg = ',';
			}

			if($sql != '')
			{
				DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
				DB::query('REPLACE INTO '.DB::table('goods_key').' SELECT * FROM '.DB::table('goods_temp'));
			}
		}

		return true;
    }

    function UpdateRank($index,$count)
    {
        if($index == 0)
		{
			DB::query("DELETE FROM ".DB::table('rank_statistic')." WHERE type IN ('SITE_MAX_GOODS_CLICK','SITE_MAX_GOODS_BOUGHT')");
		}

		$length = 0;
		$res = DB::query("SELECT id FROM ".DB::table('site')." WHERE status = 1 LIMIT $index,$count");
		$fields = array('SITE_MAX_GOODS_CLICK'=>'click_count','SITE_MAX_GOODS_BOUGHT'=>'bought');

		while($site = DB::fetch($res))
		{
			$length++;

			$ids = '';
			$ids_res = DB::query('SELECT id FROM '.DB::table('goods_now_key').' FORCE INDEX (site) WHERE site_id = '.$site['id']);
			while($gid = DB::fetch($ids_res))
			{
				$ids .= ','.$gid['id'];
			}

			if(!empty($ids))
				$ids = substr($ids,1);

			foreach($fields as $key => $field)
			{
				if(!empty($ids))
				{
					$max_goods = DB::fetchFirst("SELECT id,$field FROM ".DB::table('goods_now')." 
											WHERE id in ($ids) ORDER BY $field DESC,sort ASC,id DESC LIMIT 0,1");
					if($max_goods)
					{
						$statistic = DB::fetchFirst('SELECT * FROM '.DB::table('rank_statistic')."
													WHERE site_id = '$site[id]' AND type = '$key'");

						$statistic['site_id'] = $site['id'];
						$statistic['goods_id'] = $max_goods['id'];
						$statistic['nnum'] = $max_goods[$field];
						$statistic['type'] = $key;
						$statistic['statistic_time'] = TIME_UTC;
						DB::insert('rank_statistic',$statistic,false,true);
					}
				}
			}
		}

		return $length;
    }

    function UpdateGoodsMatch($index,$count)
    {
        if($index == 0)
		{
			DB::query('DELETE FROM '.DB::table('goods_area').' WHERE end_time <= '.TIME_UTC);
			DB::query('DELETE FROM '.DB::table('suppliers').' WHERE end_time <= '.TIME_UTC);
			$delete_ids = array();
			$res = 'SELECT gnm.id 
				FROM '.DB::table('goods_now_match').' AS gnm 
				LEFT JOIN '.DB::table('goods_now_key').' AS gnk ON gnk.id = gnm.id 
				WHERE gnk.id IS NULL';
			while($data = DB::fetch($res))
			{
				$delete_ids[] = $data['id'];
			}
			
			if(count($delete_ids) > 0)
			{
				DB::query('DELETE FROM '.DB::table('goods_now_match').' 
					WHERE id IN ('.implode(',',$delete_ids).')');
			}
		}

        DB::query('REPLACE INTO '.DB::table('goods_now_match').' 
            SELECT gm.id,gm.content 
            FROM '.DB::table('goods_now_key').' AS gnk 
            INNER JOIN '.DB::table('goods_match').' AS gm ON gm.id = gnk.id 
            LEFT JOIN '.DB::table('goods_now_match').' AS gnm ON gnm.id = gnk.id 
            WHERE gnm.id IS NULL LIMIT 0,'.$count);

        $length = DB::affectedRows();
        $length = intval($length);

        return $length;
    }

    function UpdateGoodsCache($time,$index)
    {
        define('TIME_UTC', $time);
		if($index == 0)
		{
			DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
			$res = DB::query("SELECT * FROM ".DB::table('auction_result')." WHERE auction_type = 1");
			while($result = DB::fetch($res))
			{
				$auction = S('auction')->getItem($result['auction_id']);
				if($auction)
				{
					if(count($auction['citys']) > 0 && $auction['citys'][0]['city_id'] > 0)
					{
						foreach($auction['citys'] as $city)
						{
							$goods_id = intval(DB::resultFirst('SELECT gn.id 
								FROM '.DB::table('auction_city_goods').' AS acg 
								LEFT JOIN '.DB::table('goods_now').' AS gn ON gn.id = acg.goods_id 
								WHERE acg.auction_id = '.$auction['id'].' 
								AND acg.site_id = '.$result['rec_id'].' 
								AND acg.city_id = '.$city['city_id']));

							if($goods_id == 0)
								$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);

							$data = array(
								'auction_id'=>$auction['id'],
								'site_id'=>$result['rec_id'],
								'city_id'=>$city['city_id'],
								'goods_id'=>$goods_id,
								'auction_sort'=>$result['rec_data']
							);

							DB::insert('auction_city_goods',$data,false,true);
						}
					}
					else
					{
						foreach($_FANWE['cache']['city']['all'] as $city)
						{
							$goods_id = intval(DB::resultFirst('SELECT gn.id 
								FROM '.DB::table('auction_city_goods').' AS acg 
								LEFT JOIN '.DB::table('goods_now').' AS gn ON gn.id = acg.goods_id 
								WHERE acg.auction_id = '.$auction['id'].' 
								AND acg.site_id = '.$result['rec_id'].' 
								AND acg.city_id = '.$city['id']));
							if($goods_id == 0)
								$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);

							$data = array(
								'auction_id'=>$auction['id'],
								'site_id'=>$result['rec_id'],
								'city_id'=>$city['id'],
								'goods_id'=>$goods_id,
								'auction_sort'=>$result['rec_data']
							);

							DB::insert('auction_city_goods',$data,false,true);
						}
					}
				}
			}
		}
		elseif($index == 1)
		{
			include_once import('function/cache');
        	updateCache('goods');
		}
		elseif($index == 2)
		{
        	clearDir(FANWE_ROOT.'./public/tpl/caches');
		}

		return 1;
    }

	function GetCacheFiles()
	{
		$files = array('setting');

		$cache_dir = FANWE_ROOT.'./core/cache';
		$cache_dir_handle = dir($cache_dir);
		while($entry = $cache_dir_handle->read())
		{
			if(!in_array($entry, array('.', '..')) && preg_match("/^([\w]+)\.cache\.php$/", $entry, $entryr) && $entryr[1] != 'setting' && substr($entry, -10) == '.cache.php' && is_file($cache_dir.'/'.$entry))
			{
				$files[] = $entryr[1];
			}
		}

		$files[] = 'clear_file';

		return $files;
	}

	function UpdateCache($file)
	{
		include_once import('function/cache');

		if($file == 'setting')
		{
			require_once import('cache/setting');
			bindCacheSetting();

			include FANWE_ROOT.'./ThinkPHP/Vendor/bbs.php';
			BBSAction::getInstance()->updateSetting();
		}
		elseif($file == 'clear_file')
		{
			clearDir(FANWE_ROOT.'./public/tpl');
			clearDir(FANWE_ROOT.'./admin/Runtime');
			clearDir(FANWE_ROOT.'./update/Runtime');
		}
		else
		{
			require_once import('cache/'.$file);
			call_user_func('bindCache'.ucfirst($file));
		}

		return true;
	}

	/**
     * 对 MYSQL INSERT INTO 语句的values部分内容进行字符串连接
     *
     * @param array $values
     * @return string
     */
    function ImplodeInsertValues($values)
    {
        $str = '';
        $values = array_values($values);
        foreach ($values as $k =>$v)
        {
            $v = ($v === null) ? 'null' : "'" . $v . "'";
            $str = ($k == 0) ? $str . $v : $str . ',' . $v;
        }
        return $str;
    }

	function StrPosa($haystack ,$needles=array(),$offset=0)
    {
        $chr = array();
        foreach($needles as $needle){
            strpos($haystack,$needle,$offset) !== false && $chr[] = strpos($haystack,$needle,$offset);
        }
        if(empty($chr)) return false;
        return min($chr);
    }
}
?>